package com.devin.service;


import com.aliyun.oss.HttpMethod;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.event.ProgressEvent;
import com.aliyun.oss.event.ProgressEventType;
import com.aliyun.oss.event.ProgressListener;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.devin.entity.Movie;
import com.devin.exception.FileException;
import com.devin.oss.OSSUtil;
import com.devin.repository.MovieRepository;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;


@Slf4j
@Service
public class FileService implements FileServiceImpl {

    private final MovieRepository movieRepository;

    @Autowired
    public FileService(MovieRepository movieRepository) {
        this.movieRepository = movieRepository;
    }


    public void say(){
        System.out.println("hello wrold");
    }



    /**
     * 存储文件到系统
     *
     * @param file 文件
     * @return 文件名
     */
    public Boolean storeFile(MultipartFile file) {

        // 得到文件名
        String fileName = StringUtils.cleanPath(file.getOriginalFilename());
        log.info("文件名");
        log.info(fileName);

        // Check if the file's name contains invalid characters
        if(fileName.contains("..")) {
            throw new FileException("Sorry! Filename contains invalid path sequence " + fileName);
        }

        log.info("上传到oss");
        //返回文件的访问地址
        String upload = OSSUtil.upload(file, OSSUtil.FileDirType.MOVIE);
        //如果 传文件 失败直接返回  false
        if("fail".equals(upload)){
            return false;
        }
        //建造电影对象
        Movie movie = Movie.builder()
                .kind("movie")
                .createDate(new Date())
                .creator("devin")
                .face(OSSUtil.getVideoFace(fileName, OSSUtil.FileDirType.MOVIE).toString())
                .title(fileName)
                .url(upload).build();
        Movie save = movieRepository.save(movie);
       return true;
    }





}
